package info4302.books.sparql.dbpedia;

import java.util.ArrayList;
import java.util.List;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.RDFNode;

public class DBPediaSPARQLRunner {

	private static final String MOVIE_BASED_ON_BOOK_QUERY = "PREFIX dbpedia-owl: <http://dbpedia.org/ontology/>"
			+ "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>"
			+ " PREFIX foaf: <http://xmlns.com/foaf/0.1/>"
			+ "select ?moviename ?bookname where {"
			+ "?movie dbpedia-owl:basedOn ?book ."
			+ "?movie rdf:type dbpedia-owl:Film ."
			+ "?book rdf:type dbpedia-owl:Book ."
			+ "?movie foaf:name ?moviename ."
			+ "?book foaf:name ?bookname ."
			+ "}";

	public static void main(String[] args) {
		getMovieBasedOnBookPairs();
	}

	public static List<String> getMovieBasedOnBookPairs() {
		List<String> pairs = new ArrayList<String>();

		Query query = QueryFactory.create(MOVIE_BASED_ON_BOOK_QUERY);

		System.out.println("Movie based on Book:\n");

		QueryExecution qexec = QueryExecutionFactory.sparqlService(
				"http://dbpedia.org/sparql/", query);

		try {
			ResultSet results = qexec.execSelect();
			for (; results.hasNext();) {
				String pair = "";
				QuerySolution soln = results.nextSolution();
				// cast to Jena's most general node type
				RDFNode movie = soln.get("moviename");
				// print out the result
				if (movie != null) {
					System.out.println(movie.toString());
					pair += movie.toString();
					pair += " based on ";
				}
				RDFNode book = soln.get("bookname");
				// print out the result
				if (book != null) {
					System.out.println(book.toString());
					pair += book.toString();
				}
				pairs.add(pair);
			}
			System.out.println("\n");
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		finally {
			qexec.close();
		}
		return pairs;

	}

}
